import json
import requests
import allure
from common.recordlog import logs
from common.read_yaml import ReadYamlData
import pytest

from conf import setting


class SendRequests(object):
    """
    封装接口的请求
    """

    def __init__(self):
        self.read = ReadYamlData()

    def send_request(self, **kwargs):
        cookie = {}
        session = requests.session()
        result = None
        try:
            result = session.request(**kwargs)
            set_cookie = requests.utils.dict_from_cookiejar(result.cookies)
            if set_cookie:
                cookie['cookie'] = set_cookie
                self.read.write_yaml_data(cookie)
                logs.info(f'Cookies:{cookie}')
            logs.info(f'接口实际返回结果:{result.json()}')
        except requests.exceptions.ConnectionError:
            logs.error('接口链接服务器异常')
            pytest.fail('接口请求异常')
        except requests.exceptions.HTTPError:
            logs.error('http异常')
            pytest.fail('http请求异常')
        except requests.exceptions.RequestException as e:
            logs.error(e)
            pytest.fail('请求异常')
        return result

    def run_main(self, name, url, case_name, header, method, cookies=None, file=None, **kwargs):
        """
        接口请求函数
        :param name:接口名称
        :param url: 接口地址
        :param case_name: 测试用例名称
        :param header: 请求头
        :param method: 请求方式
        :param cookies:
        :param kwargs:
        :return:
        """
        try:
            # 收集报告日志信息
            logs.info(f'接口名称:{name}')
            logs.info(f'接口请求地址:{url}')
            logs.info(f'接口请求方式:{method}')
            logs.info(f'测试用例名称:{case_name}')
            logs.info(f'请求头:{header}')
            logs.info(f'cookies:{cookies}')
            # 处理请求参数
            req_params = json.dumps(kwargs, ensure_ascii=False)
            if 'data' in kwargs.keys():
                logs.info(f'请求参数:{kwargs}')
                allure.attach(req_params,f'请求参数：{req_params}',allure.attachment_type.TEXT)
            elif 'json' in kwargs.keys():
                logs.info(f'请求参数:{kwargs}')
                allure.attach(req_params, f'请求参数：{req_params}', allure.attachment_type.TEXT)
            elif 'params' in kwargs.keys():
                logs.info(f'请求参数:{kwargs}')
                allure.attach(req_params, f'请求参数：{req_params}', allure.attachment_type.TEXT)
            else:
                logs.info(f'请求参数:{req_params}')
                allure.attach(req_params, f'请求参数：{req_params}', allure.attachment_type.TEXT)
        except  Exception as e:
            logs.error(e)
        response = self.send_request(method=method, url=url, headers=header, cookies=cookies, files=file,timeout=setting.API_TIMEOUT, verify=False,
                                     **kwargs)

        return response


# if __name__ == '__main__':
#     send = SendRequests()
#     url = "http://127.0.0.1:8787/coupApply/cms/goodsList"
#     data = {
#         "msgType": "getHandsetListOfCust",
#         "page": 1,
#         "size": 20
#     }
#     res = send.run_main(url, data, header=None, method='get')
#     print(res)
